﻿using System;
using System.IO;
using System.Linq;
using System.Reflection;

namespace ERP.Core.Configuration
{
    public static class WebContentDirectoryFinder
    {
        public static string CalculateContentRootFolder()
        {
            var coreAssemblyDirectoryPath = Path.GetDirectoryName(Assembly.GetAssembly(typeof(WebContentDirectoryFinder)).Location);
            if (coreAssemblyDirectoryPath == null)
            {
                throw new Exception("Could not find location of ERP.Core assembly!");
            }
            var directoryInfo = new DirectoryInfo(coreAssemblyDirectoryPath);
            while (!DirectoryContains(directoryInfo.FullName, "ERP.sln"))
            {
                directoryInfo = directoryInfo.Parent ?? throw new Exception("Could not find content root folder!");
            }

            var webMvcFolder = Path.Combine(directoryInfo.FullName, "ERP.Web.Mvc");
            if (Directory.Exists(webMvcFolder))
            {
                return webMvcFolder;
            }
            throw new Exception("Could not find root folder of the webMvc project!");
        }
        private static bool DirectoryContains(string directory, string fileName)
        {
            return Directory.GetFiles(directory).Any(filePath => string.Equals(Path.GetFileName(filePath), fileName));
        }

    }
}
